package loader;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class FileClassLoader extends ClassLoader {
	/**
	 * 
	 * @param name class文件路径
	 * @param className 完整类名
	 * @return
	 * @throws ClassNotFoundException
	 */
	public Class<?> findClass(String name,String className) throws ClassNotFoundException { 
        byte[] classData = getClassData(name); 
        
        if (classData == null) { 
            throw new ClassNotFoundException(); 
        } 
        else { 
            return defineClass(className, classData, 0, classData.length); 
        } 
    } 

	private byte[] getClassData(String path) { 
        try { 
            InputStream ins = new FileInputStream(path); 
            ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
            int bufferSize = 4096; 
            byte[] buffer = new byte[bufferSize]; 
            int bytesNumRead = 0; 
            while ((bytesNumRead = ins.read(buffer)) != -1) {
                baos.write(buffer, 0, bytesNumRead); 
            } 
            ins.close();
            return baos.toByteArray(); 
        } catch (IOException e) { 
            e.printStackTrace(); 
        } 
        return null; 
    }
}